package cn.billho.popcache.core.key;


import cn.billho.popcache.core.util.ReflectionUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DefaultKeyGenerator implements IKeyGenerate {
    @Override
    public String buildKey(String keyPattern, Class<?>[] parameterTypes, Object[] arguments) {
        String key = keyPattern;
        if (key.indexOf("{") >= 0) {
            Pattern pattern = Pattern.compile("(?<=\\{)\\d+(\\.?[\\w]+)*(?=\\})");
            Matcher matcher = pattern.matcher(key);
            while (matcher.find()) {
                String tmp = matcher.group();
                String express[] = matcher.group().split("\\.");
                String i = express[0];
                int index = Integer.parseInt(i) - 1;
                Object value = arguments[index];
                if (parameterTypes[index].isAssignableFrom(List.class)) {
                    List result = (List) arguments[index];
                    value = result.get(0);
                }
                if (value == null || value.equals("null")) {
                    value = "";
                }
                else {
                    if (express.length > 1) {
                        for (int idx = 1; idx < express.length && null != value; idx++) {
                            String field = express[idx];
                            value = ReflectionUtils.getFieldValue(value, field);
                        }
                    }
                }
                String rSt = null == value ?"":value.toString();

                key = key.replace("{" + tmp + "}", rSt);
            }
        }

        return key;
    }
}
